/**
 * @author chuwk
 * @version 1.0
 * @param {string} reqId           根据reqId获取当前点击的feature数据，获取master的feature数据时，reqId为-1
 * @param {string} fetureId        根据featureId获取master数据
 * @param {string} sys             根据sys，判断当前登录的系统名
 * @param {string} panelTree       判断是否是功能点树页面 tree：为功能点树页面
 * @param {string} readOnly        页面是否是只读模式  true:只读
 * @param {object} selectedBranch  获取左侧选中节点的数据（触发方法通过广播方式实现）
 * @param {boolean} doCompare      是否显示左侧编辑框
 */

angular.module('app').component('winitFeaturePanel', {
    templateUrl: getTemplateUrl('matrix/component/tpl/winitFeaturePanel.html'),
    bindings: {
        reqId          : "<",
        featureId      : "<",
        prdData        : "<",
        isPrd          : "@",
        configId       : "<",
        selectedBranch : "<",
        sys            : "=",
        doCompare      : "@",
        showHeader     : "@",
        panelType      : "@",    //true：功能树   false：编辑页面
        readOnly       : "@",    //true：只读模式 false：编辑模式
        showCompare    : "@",    //true：比较     false：不显示比较
        showMasterCompare: "@",
        featureIndex   : '@',
        prevData        : "<",    //比较数据一
        nextData        : "<"     //比较数据二
    },
    controller: function ($scope, $rootScope, $stateParams, $http, $timeout, $q, editableOptions, editableThemes, lodash) {
        var self = this;
        editableThemes.bs3.inputClass = 'input-sm';
        editableThemes.bs3.buttonsClass = 'btn-sm';
        editableOptions.theme = 'bs3';
        $scope.info = {
            featureType   : config_feature_details_type,
            featureId     : "",
            selectedRoles : [],    //已选择的角色集
            sltMasterRoles: [],    //已选择master的角色集
            roleList      : [],    //全部角色集
            selectedPSC   : [],    //已选择PSC集
            sltMasterPSC  : [],    //已选择master的PSC集
            pscList       : [],    //全部PSC集
            selectedSU    : [],    //已选择SU集
            sltMasterSU   : [],    //已选择master的SU集
            suList        : [],    //全部SU集
            nodeName      : "",    //当前选中节点名称
            nodePath      : "",    //当前选中节点路径
            editPagePath  : "",    //brd等页面路径
            reqName       : "",    //节点已关联的req名称
            originalAttr  : "",    //原始attr，比较修改的时候用
            showPanelBody : true,  //true: 显示req信息       false：显示巨幕提示
            isCrtReq      : false, //true：功能点属于当前req  false：不属于
            isDefaultReq  : false, //true：reqId等于-1       false：不等于
            isPanelType   : true,  //true：功能树            false：编辑页面
            isColSm5      : "col-sm-5", //true：显示col-sm-10     false：col-sm-5
            isOnlyMaster  : false,  //true：只显示master数据
            showPantlStyle: "panel panel-info",
            isReqSnapshot : false,
            reqList       : [],
            hasRelate     : false,
            seniorElement : false,
            isCompare     : false,
            showCompare   : false,
            isShowMaster  : false,
            isShowMasterCol: "col-sm-10",
            showMasterSwitch: false,
            isShowReq     : true,
            isReadOnly    : true,
            branchType    : true,
            currentType   : self.panelType == "tree" ? (self.featureId +"current") : (self.featureId +"current"),   //当前状态
            reqId         : "-1",
            sltFeatureTypeItem: "",
            sltMasterFeatureTypeItem: "",
        };
        $scope.initAttr = {
            feature_name     : "",
            feature_desc     : "",
            feature_in       : "",
            feature_out      : "",
            feature_abnormal : "",
            feature_logic    : "",
            feature_role     : "",
            feature_type     : "",
            feature_psc      : "",
            feature_su       : "",
            feature_checked  : "",
            version          : "",
            master_version   : "",
            req_snapshot     : "",
            feature_note     : ""
        }
        $scope.metaData = {
            feature_name     : "",
            feature_role     : "",
            feature_desc     : "",
            feature_type     : "",
            feature_in       : "",
            feature_out      : "",
            feature_abnormal : "",
            feature_logic    : "",
            feature_psc      : "",
            feature_su       : "",
            feature_checked  : "",
            version          : "",
            master_version   : "",
            req_snapshot     : "",
            feature_note     : ""
        };
        $scope.master = {
            feature_name     : "",
            feature_role     : "",
            feature_desc     : "",
            feature_type     : "",
            feature_in       : "",
            feature_out      : "",
            feature_abnormal : "",
            feature_logic    : "",
            feature_psc      : "",
            feature_su       : "",
            feature_checked  : "",
            version          : "",
            master_version   : "",
            req_snapshot     : "",
            feature_note     : ""
        };
        //调用winitFeaturePanel时，默认执行的方法
        self.$onChanges = function(data) {
            $scope.info.currentType = self.panelType == "tree" ? (self.featureId +"current") : (self.featureId +"current");
            $rootScope.showPanelLoading();
            if(self.panelType == "tree") {
                //此时加载功能树页面（1：$stateParams.reqId != -1   2: $stateParams.reqId == -1）
                $scope.info.isPanelType = true;
                $scope.info.nodeName    = self.selectedBranch.name;
                $scope.info.featureId   = self.selectedBranch.id;
                // $scope.info.isShowMaster = true;
                // $scope.info.isShowMasterCol = "col-sm-5";
                $scope.info.isShowMaster = false; //cwk--update
                $scope.info.isShowMasterCol = "col-sm-10";  //cwk-update
                if($stateParams.reqId != "-1") {
                    //此时加载(1：$stateParams.reqId != -1)
                    $scope.info.isOnlyMaster = false;
                    // $scope.info.isColSm5     = "col-sm-5";
                    $scope.info.isColSm5     = "col-sm-10"; //cwk-update
                    $scope.info.isCrtReq     = (self.selectedBranch.reqId == $stateParams.reqId) ? true : false;
                    if(self.selectedBranch.nodeType == undefined) {
                        //当前选中的节点时req节点
                        $scope.info.isDefaultReq  = false;
                        $scope.info.nodePath      = self.selectedBranch.path;
                        $scope.info.nodeName      = self.selectedBranch.featureName;
                        $scope.info.showPanelBody = true;
                        // $scope.info.showCompare   = true;
                        $scope.info.showCompare   = false;  //cwk-update
                        $scope.info.showPantlStyle= "panel panel-info";
                        getFeatureByType("req");
                        getFeaturesByReqId();
                    } else {
                        //当前选中的节点为menu，page节点
                        $scope.info.isDefaultReq  = false;
                        $scope.info.nodePath      = "";
                        $scope.info.showPanelBody = false;
                        $scope.info.showCompare   = false;
                        $scope.info.showPantlStyle= "panel panel-default";
                    }
                } else {
                    //此时加载(2: $stateParams.reqId == -1)
                    $scope.info.isDefaultReq = true;
                    $scope.info.isOnlyMaster = true;
                    $scope.info.isColSm5     = "col-sm-10";
                    if(self.selectedBranch.nodeType == undefined) {
                        $scope.info.showPanelBody = true;
                        $scope.info.showPantlStyle= "panel panel-info";
                        $scope.info.nodePath      = self.selectedBranch.path;
                        $scope.info.nodeName      = self.selectedBranch.featureName;
                        getFeatureByType("master");
                        getFeaturesByReqId();
                    } else {
                        $scope.info.showPanelBody = false;
                        $scope.info.showPantlStyle= "panel panel-default";
                        $scope.info.nodePath      = "";
                        $scope.info.nodeName      = self.selectedBranch.name;
                    }
                }
            } else {
                $scope.info.isPanelType   = false;
                $scope.info.isDefaultReq  = false;
                $scope.info.nodePath      = "";
                $scope.info.showPanelBody = true;
                $scope.info.featureId     = self.featureId;
                $scope.info.isColSm5      = "col-sm-5";
                $scope.info.isCrtReq      = self.readOnly == "true" ? false : true;
                $scope.info.showCompare   = self.showCompare == "true" ? true : false;
                $scope.info.showMasterSwitch = self.showMasterCompare == "true" ? true : false;
                $scope.info.isShowMasterCol = self.showMasterCompare == "false" ? "col-sm-5" : "col-sm-10";
                $scope.info.isShowMaster  = self.showMasterCompare == "false" ? true : false;
                
                if(self.prevData || self.nextData){
                   $scope.info.ifFeature=true;
                   $scope.info.isShowMaster=false;
                   $scope.info.isShowMasterCol = "col-sm-10"
                   $scope.metaData = self.prevData;
                   $scope.metaData.feature_name = self.prevData.feature_name;
                   if(self.nextData){
                       $scope.info.isShowMaster=true;
                       $scope.master =self.nextData;
                       $scope.master.feature_name = self.nextData.feature_name;
                       $scope.info.isShowMasterCol = "col-sm-5";
                   }
                }else{
                    getFeatureByType("req");
                }
                //getFeaturesByReqId();
            }
            if(self.readOnly == "false") {
                $scope.info.isReadOnly = false;
            }
            $scope.info.reqId = $stateParams.reqId;
            if($stateParams.reqId == "-1") {
                console.log("当前req为-1");
                $scope.info.currentType = "online";
                if(self.selectedBranch){
                    $scope.info.branchType = self.selectedBranch.nodeType ? true : false;
                }
            }
            if(self.panelType == "tree" && $stateParams.reqId) {
                $scope.info.branchType = self.selectedBranch.nodeType ? true : false;
            }
            $rootScope.hidePanelLoading();
        };

        $scope.switchFeatureType = function(item) {
            if($stateParams.reqId != "-1") {
                $scope.metaData.feature_type = item.key;
            } else {
                $scope.master.feature_type = item.key;
            }
            $scope.updateFeatureAttr();
        }

        //切换状态
        $scope.clickStatus = function(type) {
            switch(type) {
                case "current":
                    $scope.info.isShowReq = true;
                    $scope.info.isShowMaster = false;
                    $scope.info.isShowMasterCol = "col-sm-10";
                    $scope.info.isColSm5 = "col-sm-10"; 
                break;
                case "online": 
                    $scope.info.isShowReq = false;
                    $scope.info.isShowMaster = true;
                    $scope.info.isShowMasterCol = "col-sm-10";
                    $scope.info.isColSm5 = "col-sm-10"; 
                break;
                case "compare": 
                    $scope.info.isShowReq = true;
                    $scope.info.isShowMaster = true;
                    $scope.info.isShowMasterCol = "col-sm-5";
                    $scope.info.isColSm5 = "col-sm-5"; 
                break;
            }
        };

        $timeout(function() {
            if($stateParams.type == "true") {
                $scope.clickStatus("online");
                $scope.info.isOnlyMaster = false;
            } else {
                $scope.clickStatus("current");
                $scope.info.isOnlyMaster = true;
                $scope.info.currentType = "current";
            }
        }, 500);

        function getFeatureByConfigId(configId) {
            if(!configId) {
                $rootScope.showMessage("error", "失败", "configId未定义！");
                return false;
            }
            var url = matrix_product_url +"/config/get?configId="+ configId;
            $http.get(url).success(function(result) {
                if(result.code == "0") {
                    $scope.master.feature_desc   = result.data.kvmap.feature_desc;
                    $scope.master.feature_in     = result.data.kvmap.feature_in;
                    $scope.master.feature_logic  = result.data.kvmap.feature_logic;
                    $scope.master.feature_name   = result.data.kvmap.feature_name;
                    $scope.master.feature_out    = result.data.kvmap.feature_out;
                    $scope.master.feature_abnormal = result.data.kvmap.feature_abnormal;
                    $scope.master.feature_role   = result.data.kvmap.feature_role;
                    $scope.master.master_version = result.data.kvmap.master_version;
                    $scope.master.req_snapshot   = result.data.kvmap.req_snapshot;
                    $scope.master.version        = result.data.kvmap.version;
                    $scope.master.psc            = result.data.kvmap.psc ? result.data.kvmap.psc : "";
                    $scope.master.su             = result.data.kvmap.su ? result.data.kvmap.su : "";
                    $scope.master.note           = result.data.kvmap.note ? result.data.kvmap.note : "";
                } else {
                    $rootScope.showMessage("error", "失败", result.desc);
                }
            })
        };

        //获取feature信息
        function getFeatureByType(type) {
            if(!self.featureId) {
                return false;
            }
            var reqId = "";
            if(type == "req") {
                reqId = $stateParams.reqId == undefined ? self.reqId : $stateParams.reqId;
            } else {
                reqId = "-1";
            }
            var url = matrix_product_url + "/feature/getFeature?id=" + self.featureId + "&reqId=" + reqId + "&withAttr=1";
            if(self.sys) {
                url = url + "&sys=" + self.sys;
            }
            $rootScope.showPanelLoading();
            $http.get(url).success(function(result) {
                if(result.code == "0") {
                    if(self.isPrd == "true") {
                        result.data = [self.prdData];
                    }
                    if(result.data != null) {
                        if(result.data[0].attr == null) {
                            result.data[0].attr = {};
                        }
                        if(result.data[0].attr.feature_psc == undefined) {
                            result.data[0].attr.feature_psc = "";
                            result.data[0].attr.feature_su  = "";
                            result.data[0].attr.feature_note  = "";
                        }
                        if($stateParams.sys) {
                            getReqName();
                        } else {
                            if(self.reqId != "-1" && self.reqId != undefined) {
                                getReqName();
                            }
                        }
                        if(self.selectedBranch) {
                            $scope.info.nodeName = !self.reqId ? self.selectedBranch.name : self.selectedBranch.featureName;
                            $scope.info.nodePath = self.selectedBranch.path;
                        }
                        if(type == "req") {
                            $scope.metaData = result.data[0].attr;
                            $scope.metaData.feature_name = result.data[0].featureName;
                            if(result.data[0].attr.req_snapshot != "") {
                                if(result.data[0].attr.req_snapshot == $stateParams.reqId) {
                                    $scope.info.isDefaultReq = false;
                                    $scope.info.isCrtReq     = true;
                                    $scope.info.isColSm5     = "col-sm-5";
                                }
                            }
                            $timeout(function() {
                                $scope.info.seniorElement = result.data[0].attr.feature_checked == "true" ? true : false;
                            }, 200);
                            $scope.info.sltFeatureTypeItem = lodash.findWhere($scope.info.featureType, {key: result.data[0].featureKind});
                            $scope.info.originalAttr = angular.copy(result.data[0].attr);
                            $scope.info.editPagePath = result.data[0].path + "/" + result.data[0].featureName;
                        } else {
                            if(self.configId) {
                                getFeatureByConfigId(self.configId);
                            } else {
                                $scope.master = result.data[0].attr;   
                            }
                            if($stateParams.reqId == "-1") {
                                $scope.info.originalAttr = angular.copy(result.data[0].attr);
                            }
                            $timeout(function() {
                                $scope.info.seniorElement = result.data[0].attr.feature_checked == "true" ? true : false;
                            }, 200);
                            $scope.info.sltMasterFeatureTypeItem = lodash.findWhere($scope.info.featureType, {key: result.data[0].featureKind});
                            if($scope.master.version != undefined && $scope.metaData.version != undefined) {
                                $scope.info.isReqSnapshot = $scope.master.version == $scope.metaData.master_version ? false : true;
                            }
                        }
                    } else {
                        if(type == "req") {
                            $scope.metaData           = $scope.initAttr;
                            $scope.info.selectedRoles = [];
                            $scope.info.selectedPSC   = [];
                            $scope.info.selectedSU    = [];
                        } else {
                            $scope.master              = $scope.initAttr;
                            $scope.info.isReqSnapshot  = false;
                            $scope.info.sltMasterRoles = [];
                            $scope.info.sltMasterPSC   = [];
                            $scope.info.sltMasterSU    = [];
                            $scope.info.nodeName       = $scope.metaData.feature_name ? $scope.metaData.feature_name : "";
                            if(self.panelType == "tree") {
                                if($stateParams.reqId != "-1") {
                                    $scope.info.nodeName = self.selectedBranch.nodeType == undefined ? self.selectedBranch.featureName : "";
                                }
                            }
                        }
                    }
                    if(type == "req") {
                        getFeatureByType("master");
                    }

                    //切换功能点时，初始化为未选中
                    $scope.info.seniorElement = false;
                } else {
                    $rootScope.showMessage("error", "失败", result.desc);
                }
                $rootScope.hidePanelLoading();
            });
        };

        //根据reqId获取已关联的feature列表
        function getFeaturesByReqId() {
            $rootScope.showPanelLoading();
            var url = matrix_product_url + "/feature/getAllFeatureForReq?reqId="+ $stateParams.reqId;
            $http.get(url).success(function(result) {
                if(result.code == "0") {
                    $scope.info.reqList = result.data;
                    for(var i = 0; i < result.data.length; i++) {
                        if(result.data[i].id == self.featureId) {
                            $scope.info.isDefaultReq = false;
                            $scope.info.isCrtReq     = true; 
                            $scope.info.isColSm5     = "col-sm-5";
                            $scope.info.showPantlStyle = "panel panel-info";
                            $scope.info.hasRelate    = true; 
                            getReqName($scope.master.req_snapshot);
                            break;
                        } else {
                            if(self.panelType == "tree") {
                                $scope.info.isDefaultReq = self.selectedBranch.nodeType != undefined ? false : true;
                                $scope.info.showPantlStyle = self.selectedBranch.nodeType != undefined ? "panel panel-default" :  "panel panel-info";
                            } else {
                                $scope.info.isDefaultReq = true;
                                $scope.info.showPantlStyle = "panel panel-default";
                            }
                            $scope.info.isCrtReq     = false; 
                            $scope.info.isColSm5     = "col-sm-10";
                            $scope.info.hasRelate    = false; 
                        }
                    }
                    if(result.data.length == 0) {
                        if(self.selectedBranch) {
                            if(self.selectedBranch.nodeType == undefined) {
                                $scope.info.isDefaultReq = true;
                                $scope.info.isColSm5     = "col-sm-10";
                                $scope.info.showCompare  = false;
                            }
                        }
                    }
                } else {
                    $rootScope.showMessage("error", "失败", result.desc);
                }
                $rootScope.hidePanelLoading();
            });
        };

        //解决冲突
        $scope.resolveReq = function() {
            var confirmParams = {
                "titleData" : "提示",
                "bodyData"  : "确定要操作吗？"
            };
            $rootScope.confirmWindow(confirmParams, function (data) {
                if (data) {
                    var attrData = $scope.metaData;
                    attrData.master_version = $scope.master.version;
                    attrData.req_snapshot   = $scope.master.req_snapshot;
                    var postParams = {
                        id    : self.featureId,
                        attr  : attrData,
                        reqId : $stateParams.reqId,
                        featureKind: attrData.feature_type || ""
                    };
                    var url = matrix_product_url + "/feature/updateFeatureAttrForReq";
                    $http({
                        method  : "post",
                        url     : url,
                        data    : JSON.stringify(postParams),
                        headers : {"Content-Type": "application/json"}
                    }).success(function(result) {
                        if(result.code == "0") {
                            $scope.info.isReqSnapshot = false;
                            $rootScope.showMessage("success", "成功", "解决冲突成功！");
                        } else {
                            $rootScope.showMessage("error", "失败", result.desc);
                        }
                    });
                }
            });
        };

        //修改方法
        function editFeature() {
            var url = matrix_product_url + '/feature/featureOccupy?reqId=' + $stateParams.reqId + '&id=' + self.selectedBranch.id;
            $http.get(url).success(function(result){
                if(result.code == "0"){
                    $scope.info.isDefaultReq = false;
                    $scope.info.isCrtReq     = true;
                    $scope.info.isColSm5     = "col-sm-5";
                    $scope.metaData.feature_name = $scope.master.feature_name;
                    $scope.metaData.feature_role = $scope.master.feature_role;
                    $scope.metaData.feature_desc = $scope.master.feature_desc;
                    $scope.metaData.feature_in   = $scope.master.feature_in;
                    $scope.metaData.feature_out  = $scope.master.feature_out;
                    $scope.metaData.feature_abnormal  = $scope.master.feature_abnormal;
                    $scope.metaData.feature_logic= $scope.master.feature_logic;
                    $scope.metaData.feature_psc  = $scope.master.feature_psc;
                    $scope.metaData.feature_su   = $scope.master.feature_su;
                    $scope.metaData.feature_note   = $scope.master.feature_note;
                    $scope.metaData.master_version = $scope.master.version;
                    $scope.$emit('getFeaturesByReq', '');
                    getRoles("feature");
                    getPscOrSu("P", "feature");
                    getPscOrSu("S", "feature");
                    $rootScope.showMessage('success', '成功', '拉取分支成功！');
                } else {
                    $rootScope.showMessage("error", "失败", result.desc);
                }
            });
        }

        //声明一个方法（供mFunTree调用）
        $scope.$on('editFeature', function(event, data){
            editFeature();
        })

        //查询当前节点已被关联的reqName
        function getReqName(reqId) {
            var url = matrix_product_url + '/brdRequirement/getBrdRequirements?reqId=' + (reqId ? reqId : self.reqId);
            $http.get(url).success(function(result) {
                if(result.code == "0") {
                    if(result.data.length != 0 && result.data != undefined) {
                        $scope.info.reqName = result.data[0].reqName;
                    }
                } else {
                    $rootScope.showMessage("error", "失败", result.desc);
                }
            });
        };

        //描述，输入，输出，角色，psc，su更新方法
        $scope.updateFeatureAttr = function(type, status, data, flag) {
            if(status) {
                updateSingleAttr(status, data, "feature")
            }
            var reqId = self.panelType == "tree" ? $stateParams.reqId : self.reqId;
            var postParams =  {
                id    : self.featureId,
                reqId : reqId,
                attr  : $scope.metaData,
                featureKind: $scope.metaData.feature_type || ""
            };
            $scope.metaData.req_snapshot = reqId;
            if($stateParams.reqId == "-1") {
                if(status) {
                    updateSingleAttr(status, data, "master")
                }
                var postMasterParmas = {
                    id          : self.featureId,
                    attr        : $scope.master,
                    featureName : self.selectedBranch.featureName || $scope.metaData.feature_name,
                    featureKind : $scope.master.feature_type || ""
                };
                $scope.master.req_snapshot = reqId;
            }
            var defaultAttr = setAttrData($stateParams.reqId);
            var originalAttr = setOriginalAttr();
            if(type == "note") {
                defaultAttr.feature_note = $stateParams.reqId == "-1" ? $scope.master.feature_note : $scope.metaData.feature_note;
                originalAttr.feature_note = $scope.info.originalAttr.feature_note;
            }
            console.log(defaultAttr.feature_in);
            console.log(originalAttr.feature_in);
            if(!_.isEqual(defaultAttr, originalAttr)) {
                var url = matrix_product_url + "/feature/"+ ($stateParams.reqId == "-1" ? "updateFeature" : "updateFeatureAttrForReq");
                $http({
                    method  : "post",
                    url     : url,
                    data    : JSON.stringify($stateParams.reqId == "-1" ? postMasterParmas : postParams),
                    headers : {"Content-Type": "application/json"}
                }).success(function(result) {
                    if(result.code == "0") {
                        $scope.info.originalAttr = angular.copy($stateParams.reqId == "-1" ? $scope.master : $scope.metaData);
                        $rootScope.showMessage("success", "成功", "数据修改成功！");
                    } else {
                        $rootScope.showMessage("error", "失败", result.desc);
                    }
                });
            }
        };

        //业务逻辑更新
        $scope.saveBlurData = function(value) {
            //数据修改时，保存数据
            var reqId = self.panelType == "tree" ? $stateParams.reqId : self.reqId;
            var defaultAttr = setAttrData(reqId, "note");
            var originalAttr = setOriginalAttr("note");
            if(!_.isEqual(defaultAttr, originalAttr)){
                $scope.updateFeatureAttr("note");
            }
        };

        function updateSingleAttr(status, data, type) {
            if(type == "feature") {
                switch(status) {
                    case "desc": 
                        $scope.metaData.feature_desc = data.metaData;
                        break;
                    case "in": 
                        $scope.metaData.feature_in = data.metaData;
                        break;
                    case "logic": 
                        $scope.metaData.feature_logic = data.metaData;
                        break;
                    case "out": 
                        $scope.metaData.feature_out = data.metaData;
                        break;
                    case "abnormal": 
                        $scope.metaData.feature_abnormal = data.metaData;
                        break;
                }
            } else {
                switch(status) {
                    case "desc": 
                        $scope.master.feature_desc = data.master;
                        break;
                    case "in": 
                        $scope.master.feature_in = data.master;
                        break;
                    case "logic": 
                        $scope.master.feature_logic = data.master;
                        break;
                    case "out": 
                        $scope.master.feature_out = data.master;
                        break;
                    case "abnormal": 
                        $scope.master.feature_abnormal = data.master;
                        break;
                }
            }
        };

        function setAttrData(reqId, type) {
            var attr = {};
            if(reqId == "-1") {
                attr.feature_name     = $scope.master.feature_name;
                attr.feature_desc     = $scope.master.feature_desc;
                attr.feature_in       = $scope.master.feature_in;
                attr.feature_out      = $scope.master.feature_out;
                attr.feature_abnormal = $scope.master.feature_abnormal;
                attr.feature_role     = $scope.master.feature_role;
                attr.feature_type     = $scope.master.feature_type;
                attr.feature_psc      = $scope.master.feature_psc;
                attr.feature_checked  = $scope.master.feature_checked;
                attr.feature_su       = $scope.master.feature_su;
                attr.feature_logic    = $scope.master.feature_logic;
                if(type == "note") {
                    attr.feature_note = $scope.master.feature_note;
                }
            } else {
                attr.feature_name = $scope.metaData.feature_name;
                attr.feature_desc = $scope.metaData.feature_desc;
                attr.feature_in   = $scope.metaData.feature_in;
                attr.feature_out  = $scope.metaData.feature_out;
                attr.feature_abnormal = $scope.metaData.feature_abnormal;
                attr.feature_role = $scope.metaData.feature_role;
                attr.feature_type = $scope.metaData.feature_type;
                attr.feature_psc  = $scope.metaData.feature_psc;
                attr.feature_checked  = $scope.metaData.feature_checked;
                attr.feature_su   = $scope.metaData.feature_su;
                attr.feature_logic = $scope.metaData.feature_logic;
                if(type == "note") {
                    attr.feature_note = $scope.metaData.feature_note;
                }
            }
            return attr;
        };

        function setOriginalAttr(type) {
            var attr = {};
            attr.feature_name  = $scope.info.originalAttr.feature_name;
            attr.feature_desc  = $scope.info.originalAttr.feature_desc;
            attr.feature_in    = $scope.info.originalAttr.feature_in;
            attr.feature_out   = $scope.info.originalAttr.feature_out;
            attr.feature_role  = $scope.info.originalAttr.feature_role;
            attr.feature_type  = $scope.info.originalAttr.feature_type;
            attr.feature_psc   = $scope.info.originalAttr.feature_psc;
            attr.feature_su    = $scope.info.originalAttr.feature_su;
            attr.feature_logic = $scope.info.originalAttr.feature_logic;
            attr.feature_abnormal = $scope.info.originalAttr.feature_abnormal;
            if(type == "note") {
                attr.feature_note  = $scope.info.originalAttr.feature_note;
            }
            return attr; 
        };

        $scope.checkboxChange = function(checked) {
            // if(checked) {
            //     getRoles("feature");
            //     getPscOrSu("P", "feature");
            //     getPscOrSu("S", "feature");
            //     getRoles("master");
            //     getPscOrSu("P", "master");
            //     getPscOrSu("S", "master");
            // }
            if($stateParams.reqId != "-1") {
                $scope.metaData.feature_checked = checked ? true : false;
            } else {
                $scope.master.feature_checked = checked ? true : false;
            }
            $scope.updateFeatureAttr();
        };

        $scope.switchChange = function(status) {
            $scope.info.isCompare = status;
        };

        $scope.switchMasterChange = function(status) {
            $scope.info.isShowMaster = status;
            if(status) {
                $scope.info.isShowMasterCol = "col-sm-5";
            } else {
                $scope.info.isShowMasterCol = "col-sm-10";
            }
        };

        //获取角色集
        function getRoles(status) {
            var url = sys_config_url + "/select/get?type=FEATURE_ROLE";
            $http.get(url).success(function(result) {
                if(result.code == "0") {
                    if(status == "feature") {
                        $scope.info.selectedRoles = [];
                        $scope.info.selectedRoles = setSelectedValue(result.data.FEATURE_ROLE, $scope.metaData.feature_role ? $scope.metaData.feature_role : "", "role");
                    } else {
                        $scope.info.sltMasterRoles = [];
                        $scope.info.sltMasterRoles = setSelectedValue(result.data.FEATURE_ROLE, $scope.master.feature_role ? $scope.master.feature_role : "", "role");
                    }
                    angular.forEach(result.data.FEATURE_ROLE, function(data) {
                        data.name = data.value;
                    });
                    $scope.info.roleList = result.data.FEATURE_ROLE;
                } else {
                    $rootScope.showMessage("error", "失败", result.desc);
                }
            });
        };

        //获取PSC和SU集
        function getPscOrSu(type, status) {
            var url = matrix_product_url + '/psc/get?type=' + type;
            $http.get(url).success(function(result) {
                if(result.code == "0") {
                    if(type == "P") {
                        if(status == "feature") {
                            $scope.info.selectedPSC = [];
                            $scope.info.selectedPSC = setSelectedValue(result.data, $scope.metaData.feature_psc ? $scope.metaData.feature_psc : ",", "psc");
                        } else {
                            $scope.info.sltMasterPSC = [];
                            $scope.info.sltMasterPSC = setSelectedValue(result.data, $scope.master.feature_psc ? $scope.master.feature_psc : ",", "psc");
                        }
                        $scope.info.pscList = result.data;
                    } else {
                        if(status == "feature") {
                            $scope.info.selectedSU = [];
                            $scope.info.selectedSU = setSelectedValue(result.data, $scope.metaData.feature_su ? $scope.metaData.feature_su : ",", "su");
                        } else {
                            $scope.info.sltMasterSU = [];
                            $scope.info.sltMasterSU = setSelectedValue(result.data, $scope.master.feature_su ? $scope.master.feature_su : ",", "su");                            
                        }
                        $scope.info.suList = result.data;
                    }
                } else {
                    $rootScope.showMessage("error", "失败", result.desc);
                }
            });
        };

        //设置选中值
        function setSelectedValue(data, selectedList, type) {
            var selectedArray = [];
            if(selectedList != "") {
                angular.forEach(data, function(value, index) {
                    angular.forEach(selectedList.split(","), function(selectedValue, num) {
                        if(type == "role") {
                            if(selectedValue != "" && value.key == selectedValue) {
                                selectedArray.push(value);
                            }
                        } else {
                            if(selectedValue != "" && value.code == selectedValue) {
                                selectedArray.push(value);
                            }
                        }
                    });
                });
            }
            //console.log("data");
            //console.log(data);
            //console.log("selectedList");
            //console.log(selectedList);
            return selectedArray;
        };

        //新增选中对象
        $scope.selectValue = function(data) {
            if(data.status == "feature") {
                switch(data.type) {
                    case "role":
                        $scope.metaData.feature_role += data.item.key + ",";
                        break;
                    case "psc":
                        $scope.metaData.feature_psc += data.item.code + ",";
                        break;
                    case "su":
                        $scope.metaData.feature_su += data.item.code + ",";
                        break;
                }
            } else {
                switch(data.type) {
                    case "role":
                        $scope.master.feature_role += data.item.key + ",";
                        break;
                    case "psc":
                        $scope.master.feature_psc += data.item.code + ",";
                        break;
                    case "su":
                        $scope.master.feature_su += data.item.code + ",";
                        break;
                }
            }
            $scope.updateFeatureAttr();
        };

        //删除角色
        $scope.removeValue = function(data) {
            var item = data.item;
            var type = data.type;
            var status = data.status;
            var itemArray = "";
            var selectedData = [];
            switch(type) {
                case "role": 
                    selectedData = status == "feature" ? $scope.info.selectedRoles : $scope.info.sltMasterRoles;
                    itemArray = status == "feature" ? $scope.metaData.feature_role : $scope.master.feature_role;
                    break;
                case "psc": 
                    selectedData = status == "feature" ? $scope.info.selectedPSC : $scope.info.sltMasterPSC;
                    itemArray = status == "feature" ? $scope.metaData.feature_psc : $scope.master.feature_psc;
                    break;
                case "su": 
                    selectedData = status == "feature" ? $scope.info.selectedSU : $scope.info.sltMasterSU;
                    itemArray = status == "feature" ? $scope.metaData.feature_su : $scope.master.feature_su;
                    break;
            }
            
            var itemList = "";
            //剔除字符串中的错误数据
            angular.forEach(selectedData, function(selectedItem, num) {
                angular.forEach(itemArray.split(","), function(arr, index) {
                    if(type == "role") {
                        if(selectedItem.key == arr) {itemList += arr + ","};
                    } else {
                        if(selectedItem.code == arr) {itemList += arr + ","};
                    }
                    
                });
            });
            //删除数据
            var resultList = "";
            var itemArray = itemList.split(",");
            angular.forEach(itemArray, function(value, num) {
                if(type == "role") {
                    value == item.key ? itemArray.splice(num, 1) : resultList += value + ",";
                } else {
                    value == item.code ? itemArray.splice(num, 1) : resultList += value + ",";                    
                }
            });
            switch(type) {
                case "role":
                    status == "feature" ? $scope.metaData.feature_role = resultList : $scope.master.feature_role = resultList;
                    break;
                case "psc":
                    status == "feature" ? $scope.metaData.feature_psc = resultList : $scope.master.feature_psc = resultList;
                    break;
                case "su":
                    status == "feature" ? $scope.metaData.feature_su = resultList : $scope.master.feature_su = resultList;
                    break;
            }
            
            $scope.updateFeatureAttr();
        };

    }
});

app.filter('propsFilter', function() {
    return function(items, props) {
        var out = [];

        if (angular.isArray(items)) {
          items.forEach(function(item) {
            var itemMatches = false;

            var keys = Object.keys(props);
            for (var i = 0; i < keys.length; i++) {
              var prop = keys[i];
              var text = props[prop].toLowerCase();
              if (item[prop].toString().toLowerCase().indexOf(text) !== -1) {
                itemMatches = true;
                break;
              }
            }

            if (itemMatches) {
              out.push(item);
            }
          });
        } else {
          // Let the output be the input untouched
          out = items;
        }

        return out;
    };
});
